package com.dxb.idmr.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxb.idmr.entity.Students;
import com.dxb.idmr.entity.StudentsPapers;
import com.dxb.idmr.service.IStudentsPapersService;
import com.dxb.idmr.service.IStudentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import static com.dxb.idmr.controller.PapersController.DEFALT_PAPER_ID;

/**
 * <p>
 * 试卷学生 前端控制器
 * </p>
 *
 * @author dxb
 * @since 2020-05-01
 */
@RestController
@RequestMapping("/students-papers")
public class StudentsPapersController {

    @Autowired
    private IStudentsPapersService studentsPapersService;
    @Autowired
    private IStudentsService studentsService;

    @GetMapping("/draw")
    public List<Students> draw(int num) {
        List<Students> students = new ArrayList<>();
        if (num <= 0) {
            return students;
        }

        QueryWrapper<StudentsPapers> queryWrapper = new QueryWrapper<StudentsPapers>()
                .eq("SCORE", 100)
                .eq("PAPER_ID", DEFALT_PAPER_ID);
        List<StudentsPapers> list = studentsPapersService.list(queryWrapper);
        List<String> ids = new ArrayList<>();
        if (num < list.size()) {
            Random random = new Random();
            while (ids.size() < num) {
                StudentsPapers sp = list.get(random.nextInt(list.size()));
                if (sp.getSno() != null) {
                    ids.add(sp.getSno());
                    sp.setSno(null);
                }
            }
        } else {
            list.forEach((s) -> ids.add(s.getSno()));
        }
        if (ids.size() == 0) {
            return students;
        }
        students = studentsService.listByIds(ids);
        Collections.shuffle(students);
        return students;
    }


}
